package com.anyi.blog.controller;

import com.anyi.blog.entity.User;
import com.anyi.blog.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
@Api(tags = "认证管理")
public class UserController {
    @Autowired
    private UserService userService;


    @PostMapping("/login")
    @ApiOperation("用户登录")
    public ResponseEntity<Map<String, String>> login(@RequestBody LoginRequest request) {
        User user = userService.login(request.getUsername(), request.getPassword());
        if (user == null) {
            System.out.println("用户名或密码错误");
            return ResponseEntity.badRequest().build();
        }

//        String token = JwtUtil.generateToken(user);
//
        Map<String, String> response = new HashMap<>();
        response.put("username", user.getUsername());
        response.put("role", user.getRole());
//        response.put("token", token);
//        response.put("expiresIn", String.valueOf(JwtUtil.EXPIRATION));
        return ResponseEntity.ok(response);
    }


    @Data
    public class LoginRequest {
        private String username;
        private String password;
    }


    @PostMapping("/register")
    @ApiOperation("用户注册")
    public ResponseEntity<Map<String, String>> register(@RequestBody User request) {
        User user = userService.register(request);
        if (user == null) {
            System.out.println("注册失败");
            return ResponseEntity.badRequest().build();
        }

//        String token = JwtUtil.generateToken(user);
//
        Map<String, String> response = new HashMap<>();
        response.put("username", user.getUsername());
        response.put("role", user.getRole());
//        response.put("token", token);
//        response.put("expiresIn", String.valueOf(JwtUtil.EXPIRATION));
        return ResponseEntity.ok(response);
    }

}
